var secretOrPrivateKey = "This is perfect projects.";
var adminPrivateKey = "admin projects.";
const Token = require('./Token')


module.exports= function (req,res,next) {
   // 获取请求头中的Authorization认证字符
  if (/login/.test(req.path)) {
    next()
  } else if (/regist/.test(req.path)) {
    next();
  } else if (/upload/.test(req.path)) {
    next();
  } else if (/getuserfollow/.test(req.path)||/getuserfans/.test(req.path)
  ||/getuserselfvideo/.test(req.path) ||/getuserinfo/.test(req.path)
  ||/getuserlikevideo/.test(req.path)||/getrecommentvideo/.test(req.path)
  ||/getvideosearch/.test(req.path)||/getusersearch/.test(req.path)
  ||/findBoards/.test(req.path)
  ||/getreplycomment/.test(req.path)||/getvideocomment/.test(req.path)) {
    // 不需要token的接口
    if (req.get('Authorization') == null) {
      req.query = {...req.query,loginUserid:undefined}
      next()
    }else{
      let authorization = req.get('Authorization').split(' ')[1]
      let data = Token.decrypt(authorization,secretOrPrivateKey);
      if (data.token) {
        req.query = {...req.query,loginUserid:data.data.userid}
        return next();
        //有效token
      }else{
        //无效token,查看是否是admin账号
        let adminPrivateData = Token.decrypt(authorization,adminPrivateKey); 
        if(adminPrivateData.token){
          req.query = {...req.query,loginUserid:data.data.userid}
          return next();
        }else{
          req.query = {...req.query,loginUserid:undefined}
          return next();
        }
      }
    }
  } else {
    if (req.get('Authorization') == null) {
     return res.status(403).send('认证无效，请重新登录。');
    }
    let authorization = req.get('Authorization').split(' ')[1]
          let data = Token.decrypt(authorization,secretOrPrivateKey);  //将请求头的token取出解密
      if (data.token) {
        req.query = {...req.query,loginUserid:data.data.userid}
        return next();
        //有效token
      }else{
        //无效token,查看是否是admin账号
        // console.log(authorization);
        let adminPrivateData = Token.decrypt(authorization,adminPrivateKey);
        // console.log(adminPrivateData); 
        if(adminPrivateData.token){
          req.query = {...req.query,loginUserid:adminPrivateData.data.userid}
          return next();
        }else{
          return res.status(403).send('认证无效，请重新登录。');
        }
      }
  }
}
